﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MESQWinform;
using MesProjectWinform.BasicData.Entity;
using Newtonsoft.Json;
using Ces.Entity;
using MesProjectWinform.Public.Common;
using System.IO;
using System.Net.Http;

namespace MesProjectWinform.BasicData.基础实现.chan
{
    public partial class chanCreate : DevExpress.XtraEditors.XtraForm
    {
        // 存储车间信息的列表
        private List<WorkShop> workshopList = new List<WorkShop>();
        // 存储选中的车间ID
        private long selectedWorkshopId;
        // API基础地址
        private readonly string apiBaseUrl = "http://47.110.243.157:5052";
        // 序号存储文件路径
        private readonly string sequenceFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ProductionLineSequence.txt");
        // 日期格式化字符串
        private readonly string dateFormat = "yyMMdd";
        
        public chanCreate()
        {
            InitializeComponent();
            
            // 设置窗体居中显示
            this.StartPosition = FormStartPosition.CenterScreen;
            
            // 窗体加载时获取车间列表
            this.Load += ChanCreate_Load;
            // 添加车间选择事件
            comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged_1;
        }
        
        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private async void ChanCreate_Load(object sender, EventArgs e)
        {
            // 设置产线编码文本框为只读
            textEdit1.Properties.ReadOnly = true;
            // 生成自动递增编码
            GenerateAutoIncrementCode();
            // 加载车间数据
            await LoadAllWorkshops();
        }
        
        /// <summary>
        /// 生成自动递增的编码
        /// </summary>
        private void GenerateAutoIncrementCode()
        {
            try
            {
                // 生成当前日期部分 格式：yyMMdd
                string today = DateTime.Now.ToString(dateFormat);
                
                // 读取序号文件，获取当前最大序号
                int currentSequence = 1; // 默认从1开始
                string lastDate = string.Empty;
                
                if (File.Exists(sequenceFilePath))
                {
                    string[] fileContent = File.ReadAllLines(sequenceFilePath);
                    if (fileContent.Length >= 2)
                    {
                        lastDate = fileContent[0]; // 第一行存储日期
                        int.TryParse(fileContent[1], out currentSequence); // 第二行存储序号
                        
                        // 如果是新的一天，重置序号为1
                        if (lastDate != today)
                        {
                            currentSequence = 1;
                        }
                        // 注意：此处不自增序号，只显示当前序号
                    }
                }
                
                // 格式化为4位数字，前面补0
                string serialPart = currentSequence.ToString().PadLeft(4, '0');
                
                // 组合最终的编码：CJ + 日期 + 4位序号
                string finalCode = "CX" + today + serialPart;
                
                // 设置到文本框
                textEdit1.Text = finalCode;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"生成产线编码时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // 生成失败时使用默认编码
                textEdit1.Text = "CX" + DateTime.Now.ToString(dateFormat) + "0001";
            }
        }

        /// <summary>
        /// 保存成功后更新序号
        /// </summary>
        private void UpdateSequenceAfterSuccess()
        {
            try
            {
                // 获取当前日期
                string today = DateTime.Now.ToString(dateFormat);
                int currentSequence = 1;
                
                // 读取当前序号
                if (File.Exists(sequenceFilePath))
                {
                    string[] fileContent = File.ReadAllLines(sequenceFilePath);
                    if (fileContent.Length >= 2)
                    {
                        string lastDate = fileContent[0];
                        int.TryParse(fileContent[1], out currentSequence);
                        
                        // 如果是新的一天，重置序号为1
                        if (lastDate != today)
                        {
                            currentSequence = 1;
                        }
                        else
                        {
                            // 否则序号加1
                            currentSequence++;
                        }
                    }
                }
                
                // 保存更新后的序号到文件
                using (StreamWriter writer = new StreamWriter(sequenceFilePath, false))
                {
                    writer.WriteLine(today);
                    writer.WriteLine(currentSequence.ToString());
                }
            }
            catch (Exception ex)
            {
                // 更新序号失败不影响主流程，可以静默处理
                Console.WriteLine($"更新序号失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 重置页面    
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            // 重新生成自动递增编码
            GenerateAutoIncrementCode();
            // 清空其他输入框
            textEdit2.Text = string.Empty; // 产线名称
            comboBox1.SelectedIndex = -1; // 清空车间选择
            memoEdit1.Text = string.Empty; // 产线描述
            //产线属性可以为空
            labelControl3.Text = "车间名称:"; // 清空车间名称
        }
        
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button2_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrEmpty(textEdit2.Text.Trim()))
                {
                    XtraMessageBox.Show("产线名称不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textEdit2.Focus();
                    return;
                }

                if (comboBox1.SelectedIndex == -1)
                {
                    XtraMessageBox.Show("请选择所属车间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    comboBox1.Focus();
                    return;
                }

                // 获取表单数据
                string productionlineCode = textEdit1.Text.Trim();
                string productionlineName = textEdit2.Text.Trim();
                string description = memoEdit1.Text.Trim();
                //属性可以为空
                string attributes = " ";
                
                // 获取选中的车间ID和名称
                string workshopId = selectedWorkshopId.ToString();
                string workshopName = comboBox1.SelectedItem?.ToString() ?? "";

                // 创建产线对象
                Productionline productionline = new Productionline
                {
                    IsDeleted = false,
                    CreatedBy = "admin",
                    CreatedTime = DateTime.Now,
                    UpdatedBy = "张三",
                    UpdatedTime = DateTime.Now,
                    Productionlinecode = productionlineCode,
                    Productionlinename = productionlineName,
                    Workshopid = workshopId,
                    Workshopname = workshopName, // 设置车间名称
                    Productionlinedescription = description,
                    Productionlineattributes = attributes
                };

                // 将对象序列化为JSON
                string jsonData = JsonConvert.SerializeObject(productionline);
                StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                // 使用HttpClient直接发送请求
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(apiBaseUrl);
                    HttpResponseMessage response = await client.PostAsync("/api/Productionline/AddProductionline", content);
                    
                    string result = await response.Content.ReadAsStringAsync();
                    var responseObj = JsonConvert.DeserializeObject<dynamic>(result);
                    
                    // 修改：无论HTTP状态如何，都尝试解析返回的内容
                    if (responseObj?.code == 200 || response.IsSuccessStatusCode)
                    {
                        // 保存成功后更新序号
                        UpdateSequenceAfterSuccess();
                        
                        // 显示成功消息
                        XtraMessageBox.Show("添加产线成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        
                        // 清空表单
                        button1_Click(null, null);
                        
                        // 关闭窗口
                        this.DialogResult = DialogResult.OK;
                    }
                    else
                    {
                        string errorMessage = responseObj?.message?.ToString() ?? "未知错误";
                        XtraMessageBox.Show($"添加产线失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        
                        // 如果实际上添加成功了，关闭窗口
                        if (responseObj?.Data != null)
                        {
                            // 添加成功时更新序号
                            UpdateSequenceAfterSuccess();
                            this.DialogResult = DialogResult.OK;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"添加产线时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 下拉获取渠道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            try
            {
                if (comboBox1.SelectedIndex >= 0 && workshopList != null && workshopList.Count > comboBox1.SelectedIndex)
                {
                    // 获取选中的车间对象
                    WorkShop selectedWorkshop = workshopList[comboBox1.SelectedIndex];
                    // 保存选中车间的ID
                    selectedWorkshopId = selectedWorkshop.Id;
                    // 显示车间名称
                    labelControl3.Text = $"车间名称: {selectedWorkshop.Workshopname}";
                }
                else
                {
                    labelControl3.Text = "车间名称:";
                }
            }
            catch (Exception ex)
            {
                // 捕获并记录异常，但不中断用户操作
                System.Diagnostics.Debug.WriteLine($"车间选择错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 加载所有车间数据
        /// </summary>
        private async Task LoadAllWorkshops()
        {
            try
            {
                // 使用HttpClient直接发送请求获取车间数据
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(apiBaseUrl);
                    HttpResponseMessage response = await client.GetAsync("/api/WorkShop/GetAllShop");
                    
                    if (response.IsSuccessStatusCode)
                    {
                        string result = await response.Content.ReadAsStringAsync();
                        var responseObj = JsonConvert.DeserializeObject<dynamic>(result);
                        
                        if (responseObj?.Data != null)
                        {
                            // 创建车间列表
                            workshopList = new List<WorkShop>();
                            
                            // 解析JSON数据到车间列表
                            if (responseObj.Data is Newtonsoft.Json.Linq.JArray)
                            {
                                foreach (var item in responseObj.Data)
                                {
                                    WorkShop workshop = new WorkShop
                                    {
                                        Id = item.Id,
                                        Workshopcode = item.Workshopcode?.ToString(),
                                        Workshopname = item.Workshopname?.ToString(),
                                        Workshopdescription = item.Workshopdescription?.ToString()
                                    };
                                    workshopList.Add(workshop);
                                }
                                
                                // 清空下拉框
                                comboBox1.Items.Clear();
                                
                                // 将车间名称添加到下拉框
                                foreach (var workshop in workshopList)
                                {
                                    comboBox1.Items.Add(workshop.Workshopname);
                                }
                                
                                // 如果有数据，默认选择第一项
                                if (comboBox1.Items.Count > 0)
                                {
                                    comboBox1.SelectedIndex = 0;
                                }
                                else
                                {
                                    comboBox1.SelectedIndex = -1;
                                    labelControl3.Text = "车间名称:";
                                }
                                
                                return;
                            }
                        }
                    }
                    
                    // 如果API请求失败或没有返回有效数据，使用模拟数据
                    InitializeDefaultWorkshops();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载车间数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
                // 出错时也确保下拉框有数据可选
                InitializeDefaultWorkshops();
            }
        }
        
        /// <summary>
        /// 初始化默认车间数据，确保即使API失败也有可用数据
        /// </summary>
        private void InitializeDefaultWorkshops()
        {
            try
            {
                // 创建模拟车间数据
                workshopList = new List<WorkShop>
                {
                    new WorkShop { Id = 1, Workshopcode = "CJ001", Workshopname = "总装车间", Workshopdescription = "总装车间" },
                    new WorkShop { Id = 2, Workshopcode = "CJ002", Workshopname = "电池车间", Workshopdescription = "电池组装车间" },
                    new WorkShop { Id = 3, Workshopcode = "CJ003", Workshopname = "测试车间", Workshopdescription = "产品测试车间" }
                };
                
                // 清空下拉框
                comboBox1.Items.Clear();
                
                // 将车间名称添加到下拉框
                foreach (var workshop in workshopList)
                {
                    comboBox1.Items.Add(workshop.Workshopname);
                }
                
                // 选择第一项
                if (comboBox1.Items.Count > 0)
                {
                    comboBox1.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"初始化默认车间数据失败: {ex.Message}");
            }
        }
    }
}